import React, { Component } from 'react';
import ReactDom from 'react-dom';
import util from "@/common/util";
import layer from "@/common/layer";
import Rate from '@/Components/rate';
import DDView from '@/Components/ddview';
import InlinePicker from '@/Components/inlinepicker';
import ReactSwiper from 'reactjs-swiper';
import axios from 'axios';
import { relative } from 'path';
import jquery from 'jquery';

class Creditcardshare extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tellphone: '',
            username: '',
            second: 0,
            code: '',
            isreg: false
        }
        this.valids = [
            {
                key: 'tellphone',
                func(str) {
                    if (str.length !== 11) {
                        jquery(".errormsg").html("手机号码格式错误")
                        return false
                    } else {
                        jquery(".errormsg").empty()
                    }
                    return true
                }
            },
            {
                key: 'code',
                func(str) {
                    if (str.length === 0) {
                        jquery(".errormsg").html("验证码不能为空")
                        return false
                    } else {
                        jquery(".errormsg").empty()
                    }
                    return true
                }
            },
            {
                key: 'username',
                func(str) {
                    if (str.length === 0) {
                        jquery(".errormsg").html("姓名不能为空")
                        return false
                    }
                    return true
                }
            }
        ]
    }

    async sendcode() {
        var wechatcode = util.getQuery().code;
        let res = await util.rjax({
            url: '/wxAuthenticate/getOpenId?code=' + wechatcode,
            type: 'post',
        }).catch((res) => {
            console.log("catch:" + res)
        })

        if (res) {
            console.log("if(res):" + res)
            sessionStorage.setItem("openid", res.data.openId)
            // this.isreg()
        }
    }

    componentDidMount() {
        if (util.getQuery().code) {
            var openid = sessionStorage.getItem("openid")
            if (!openid || openid === 'null') {
                this.sendcode()
            }
        }
        else {
            var otheropenid = util.getQuery().uid
            if (!otheropenid || otheropenid === 'null') {
            } else {
                sessionStorage.setItem("otheropenid", otheropenid)
            }
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxeaccffdd3826280c&redirect_uri=http%3a%2f%2fwww.rongsue.com%2fwechat%2fcreditcardshare.html&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect`
        }

        let getconfig = async function () {
            let res = await util.rjax({
                url: "/wx/getwx?url=" + encodeURIComponent(window.location.href.split('#')[0]),
                type: "POST"
            })

            if (res) {
                wx.config({
                    debug: false,
                    appId: 'wxeaccffdd3826280c', // 必填，公众号的唯一标识
                    timestamp: parseInt(res.data.timestamp),// 必填，生成签名的时间戳
                    nonceStr: res.data.nonceStr,// 必填，生成签名的随机串
                    signature: res.data.signature,// 必填，签名
                    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']// 必填，需要使用的JS接口列表
                })
            }
        }
        getconfig()
        var openid = sessionStorage.getItem("openid");
        wx.ready(function () {
            //朋友圈
            wx.onMenuShareTimeline({// 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口（即将废弃）
                title: '来苏e栈夺壕礼', // 分享标题
                link: 'http://www.rongsue.com/wechat/creditcardshare.html?uid=' + sessionStorage.getItem("openid"), // 分享链接
                imgUrl: 'http://img0.rongsue.com/FgBE9gyUnl_ubTHu4IPoNydQIEE-',
                success: function (res) { },
                cancel: function (res) { },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });

            //朋友
            wx.onMenuShareAppMessage({//获取“分享给朋友”按钮点击状态及自定义分享内容接口（即将废弃）
                title: '来苏e栈夺壕礼', // 分享标题
                desc: '现金！实物奖品！实物卡！想要就来"拿"！', // 分享描述
                link: 'http://www.rongsue.com/wechat/creditcardshare.html?uid=' + sessionStorage.getItem("openid"), // 分享链接
                imgUrl: 'http://img0.rongsue.com/FgBE9gyUnl_ubTHu4IPoNydQIEE-', // 分享图标
                type: '', // 分享类型,music、video或link，不填默认为link
                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        });
    }

    async beforeSendCode() {
        if (this.state.second !== 0) { return }
        if (this.state.tellphone.length < 11) {
            jquery(".errormsg").html("手机格式错误")
            return
        } else {
            jquery(".errormsg").empty()
        }
        this.setState({
            second: 60
        });
        let time = setInterval(() => {
            if (this.state.second < 1) {
                clearInterval(time)
            } else {
                this.setState({
                    second: this.state.second - 1
                })
            }
        }, 1000)
        let phone = this.state.tellphone
        let res = await axios.get(`${util.host}/auth/code/sms`, {
            params: {
                deviceId: phone,
                phone: phone
            }
        }).catch((e) => {
            jquery(".errormsg").html(e.data.msg)
        })

        if (res.data.success) {
            jquery(".errormsg").html("验证码发送成功")
        } else {
            jquery(".errormsg").html("手机号码格式错误")
        }

    }

    async beforeSubmit() {
        for (let item of this.valids) {
            if (!item.func(this.state[item.key])) {
                return;
            }
        }
        var otheropenid = sessionStorage.getItem('otheropenid')
        let sendobj
        if (!otheropenid || otheropenid === 'null') {
            var openId = sessionStorage.getItem('openid')
            sendobj = {
                phone: this.state.tellphone,
                code: this.state.code,
                name: this.state.username,
                openId: openId
            }
        } else {
            var otherOpenId = sessionStorage.getItem('otheropenid')
            var openId = sessionStorage.getItem('openid')
            sendobj = {
                phone: this.state.tellphone,
                code: this.state.code,
                name: this.state.username,
                otherOpenId: otherOpenId,
                openId: openId
            }
        }
        let res = await util.rjax({
            url: '/invite/register',
            type: "POST",
            data: sendobj
        }).catch((e) => {
            jquery(".errormsg").html(e.data.msg)
        })
        if (res) {
            // layer.open({
            //     content: res.msg,
            //     btn: '好的'
            // })
            jquery('.apply').hide()
            if (jquery('.apply').attr('data-id') == 1) {
                window.location.href = "https://creditcardapp.bankcomm.com/applynew/front/apply/track/record.html?trackCode=A0404151586042&cardId=2"
            } else if (jquery('.apply').attr('data-id') == 0) {
                jquery('.sharedialog').show()
            }
        }
    }

    async closeshare() {
        jquery('.sharedialog').hide()
    }

    async closeapply() {
        jquery('.apply').hide()
    }

    async ruleshow() {
        jquery('.ruledet').show()
    }
    async closerule() {
        jquery('.ruledet').hide()
    }

    async share() {
        this.isreg(0)
    }
    async applycardbtn() {
        this.isreg(1)
    }

    async isreg(id) {
        var openid = sessionStorage.getItem("openid");
        let res = await util.rjax({
            url: '/invite/isRegister?openId=' + openid,
            type: 'get',
        }).catch((e) => {
            console.log("e:" + e)
        })
        if (res) {
            if (res.data === 0) {//该用户没有注册过
                jquery('.apply').attr('data-id', id).show()
                // jquery('.apply').show()
            } else if (res.data === 1) {//该用户注册过
                if (id == 0) {
                    jquery('.sharedialog').show()
                } else if (id == 1) {
                    window.location.href = "https://creditcardapp.bankcomm.com/applynew/front/apply/track/record.html?trackCode=A0404151586042&cardId=2"
                }
            }
        }
    }

    phoneChange(e) {
        this.setState({
            tellphone: e.target.value
        })
    }

    codeChange(e) {
        this.setState({
            code: e.target.value
        })
    }

    usernameChange(e) {
        this.setState({
            username: e.target.value
        })
    }

    render() {
        return (
            <div>
                <div id="guangfa">
                    <div className="bg">
                        <img src="/assets/wechat/background.png" alt="" />
                        <div className="bigtit">
                            <img src="/assets/wechat/topword.png" alt="" />
                            <p>活动时间：2018年10月15日-11月30日</p>
                        </div>

                        <div className="rule">
                            <div className="ruleitem" onClick={this.ruleshow.bind(this)}>
                                <img className="rulebtn" src="/assets/wechat/btn_rule.png" alt="" />
                                <span>活动细则</span>
                            </div>
                            <div className="ruleitem">
                                <a href="./cardshareprocess.html">
                                    <img src="/assets/wechat/btn_rule.png" alt="" />
                                    <span>参与流程</span>
                                </a>
                            </div>
                        </div>

                        <div className="card">
                            <p className="tit">交通银行Y-Power经典主题（原力黑）</p>
                            <img className="l" src="/assets/wechat/pic_creditcard.png" alt="" />
                            <div className="r">
                                <p>多处场所刷卡消费享受八折优惠</p>
                                <p>双倍积分奖励</p>
                                <p>每天可签到抽奖</p>
                                <p>仅限35岁以下用户办理</p>
                            </div>
                        </div>

                        <div className="prizelist">
                            <h4>
                                <img src="/assets/wechat/icon_leftcut.png" alt="" />
                                不限量领取，无需抽奖，无需抢兑
                               <img src="/assets/wechat/icon_rightcut.png" alt="" />
                            </h4>
                            <div className="list">
                                <div className="prize">
                                    <p className="tit">邀请10人核卡成功，可得以下礼品3选1</p>
                                    <div className="flexbox">
                                        <div className="item">
                                            <div>
                                                <img src="/assets/wechat/700.png" alt="" />
                                            </div>
                                            <p className="value">奖金700元</p>
                                        </div>
                                        <div className="item">
                                            <div>
                                                <img src="/assets/wechat/pic_projector.png" alt="" />
                                            </div>
                                            <p className="value">光米M3智能投影仪</p>
                                        </div>
                                        <div className="item">
                                            <div>
                                                <img src="/assets/wechat/pic_card.png" alt="" />
                                            </div>
                                            <p className="value">苏果卡700元</p>
                                        </div>
                                    </div>
                                </div>
                                <div className="prize">
                                    <p className="tit">邀请5人核卡成功，可得以下礼品3选1</p>
                                    <div className="flexbox">
                                        <div className="item">
                                            <div>
                                                <img src="/assets/wechat/300.png" alt="" />
                                            </div>
                                            <p className="value">奖金300元</p>
                                        </div>
                                        <div className="item">
                                            <div>
                                                <img src="/assets/wechat/pic_camera.png" alt="" />
                                            </div>
                                            <p className="value">富士相机mini7C</p>
                                        </div>
                                        <div className="item">
                                            <div>
                                                <img src="/assets/wechat/pic_card.png" alt="" />
                                            </div>
                                            <p className="value">苏果卡300元</p>
                                        </div>
                                    </div>
                                </div>
                                <div className="prize">
                                    <p className="tit">邀请2人核卡成功，可得以下礼品3选1</p>
                                    <div className="flexbox">
                                        <div className="item">
                                            <div>
                                                <img src="/assets/wechat/100.png" alt="" />
                                            </div>
                                            <p className="value">奖金100元</p>
                                        </div>
                                        <div className="item">
                                            <div>
                                                <img src="/assets/wechat/pic_juicer.png" alt="" />
                                            </div>
                                            <p className="value">美的家用榨汁机</p>
                                        </div>
                                        <div className="item">
                                            <div>
                                                <img src="/assets/wechat/pic_card.png" alt="" />
                                            </div>
                                            <p className="value">苏果卡100元</p>
                                        </div>
                                    </div>
                                </div>


                            </div>
                        </div>

                        <div className="step">
                            <h4>
                                <img src="/assets/wechat/icon_leftcut.png" alt="" />
                                简单三步，轻松获奖
                               <img src="/assets/wechat/icon_rightcut.png" alt="" />
                            </h4>
                            <div className="stepitem">
                                <span className="l">01</span>
                                <div className="r">
                                    <p>邀一邀</p>
                                    <p>邀请过去从未持有我行信用卡的亲友办卡</p>
                                </div>
                            </div>
                            <div className="stepitem">
                                <span className="l">02</span>
                                <div className="r">
                                    <p>填一填</p>
                                    <p>通过本页面分享链接给亲友填写并提交</p>
                                </div>
                            </div>
                            <div className="stepitem">
                                <span className="l">03</span>
                                <div className="r">
                                    <p>刷一刷</p>
                                    <p>朋友提交信用卡申请核卡成功</p>
                                </div>
                            </div>
                        </div>

                        <div className="activi">
                            <h4>
                                <img src="/assets/wechat/icon_leftcut.png" alt="" />
                                活动热评
                               <img src="/assets/wechat/icon_rightcut.png" alt="" />
                            </h4>
                            <div className="activitem">
                                <img className="l" src="/assets/wechat/user1.png" alt="" />
                                <div className="r">
                                    <p className="username">小旋风</p>
                                    <p className="qustion">这活动的奖励是抽奖得到吗？</p>
                                    <p className="star"><img src="/assets/wechat/icon_reply.png" alt="" />官方回复：</p>
                                    <p className="answer">你好~不是抽奖哦，只要达到邀请成功人数并且核卡（可不激活，需本人拿到卡），即可领取奖励，真实无套路哟~</p>
                                </div>
                            </div>
                            <div className="activitem">
                                <img className="l" src="/assets/wechat/user2.png" alt="" />
                                <div className="r">
                                    <p className="username">CynThia</p>
                                    <p className="qustion">怎么样算邀请成功，去哪里看？</p>
                                    <p className="star"><img src="/assets/wechat/icon_reply.png" alt="" />官方回复：</p>
                                    <p className="answer">受邀人在活动期间（由于核卡有延时,以活动结束后10个工作日内为准）完成核卡即算邀请成功。</p>
                                </div>
                            </div>
                            <div className="activitem">
                                <img className="l" src="/assets/wechat/user3.png" alt="" />
                                <div className="r">
                                    <p className="username">黄某某</p>
                                    <p className="qustion">奖励去哪领取呢？</p>
                                    <p className="star"><img src="/assets/wechat/icon_reply.png" alt="" />官方回复：</p>
                                    <p className="answer">好友受邀核卡成功人数达到后，可联系客服进行奖励领取，客服VX：suerong123。</p>
                                </div>
                            </div>
                        </div>

                        <div className="ruledet">
                            <div className="rulebox">
                                <img onClick={this.closerule.bind(this)} className="closerule" src="http://img0.rongsue.com/FibZC6pQAT8VsJCmjv5VpL_77qpH" alt="" />
                                <div className="ruleborder">
                                    <h4>活动规则</h4>
                                    <p className="ruletit">活动时间：</p>
                                    <p className="rulecont">2018年10月17日至11月30日</p>
                                    <p className="ruletit">活动对象：</p>
                                    <p className="rulecont">满18周岁的中国公民</p>
                                    <p className="ruletit">成功邀请的条件：</p>
                                    <p className="rulecont">1. 受邀人（新客户）通过邀请办卡页面申请信用卡，推荐新客户成功办理交通银行信用卡，并核发卡片，即为推荐成功；（注：邀请结果统计以受邀人交通银行下卡短信通知时间为准）<br />2. 提供成功办理客户的姓名，由后台核实数据，核实有客户姓名即可获得奖励。（举例：受邀人10月30日申请信用卡，十个工作日内有交通银行下卡短信通知，办理成功即可。）</p>
                                    <p className="ruletit">本活动新客户定义：</p>
                                    <p className="rulecont">首次申请交通银行信用卡的新用户。（注：曾申请过信用卡销户后无卡的用户，再次进行下卡，不归属新用户范围。）</p>
                                    <p className="ruletit">活动内容：</p>
                                    <p className="rulecont">邀请人在活动期间邀请人参与办理交通银行信用卡数达标即可获得权益奖励。<br />考核标准：办理成功<br />【成功邀请2人】100元现金或100元苏果卡或便携榨汁机一台<br />【成功邀请5人】300元现金或300元苏果卡或富士拍立得一台  <br />【成功邀请10人】700元现金或700元苏果卡或投影仪一台</p>
                                    <p className="explain">本次活动最终解释权归苏e栈所有。</p>
                                </div>
                                <div className="shadow"></div>
                            </div>
                        </div>

                        <div className="apply">
                            <div className="applydialog">
                                <img onClick={this.closeapply.bind(this)} className="closeapply" src="http://img0.rongsue.com/FibZC6pQAT8VsJCmjv5VpL_77qpH" alt="" />
                                <p>填写下方信息，便于后期核实领取奖品！</p>
                                <div style={{ position: "relative" }}>
                                    <span className="cityhead">姓名</span>
                                    <input type="text" className="text" autoComplete="off" placeholder="请输入姓名" value={this.state.username} onChange={this.usernameChange.bind(this)} />
                                </div>

                                <div style={{ position: "relative" }}>
                                    <span className="phonehead">+86</span>
                                    <input type="text" className="text" autoComplete="off" placeholder="请输入手机号" value={this.state.tellphone} onChange={this.phoneChange.bind(this)} maxLength="11" />
                                </div>
                                <div style={{ position: "relative" }}>
                                    <span className="codehead">验证码</span>
                                    <input type="text" className="text" autoComplete="off" placeholder="请输入验证码" value={this.state.code} onChange={this.codeChange.bind(this)} />
                                    <input type="button" className="yzbtn" value={(this.state.second === 0) ? '验证码' : `剩余${this.state.second}秒`} onClick={this.beforeSendCode.bind(this)} />
                                </div>

                                <div style={{ position: "relative" }}>
                                    <span className="errormsg"></span>
                                    <input type="button" className="btn" value="确定" onClick={this.beforeSubmit.bind(this)} />
                                </div>
                            </div>
                        </div>

                        <div className="applybtn">
                            <a className="applycard" onClick={this.applycardbtn.bind(this)} href="#">申请信用卡</a>
                            <a className="share" href="#" onClick={this.share.bind(this)}>立即邀请</a>
                        </div>

                        <div className="sharedialog" onClick={this.closeshare.bind(this)}>
                            <div className="sharediabox">
                                <img className="arrow" src="/assets/wechat/pic_arrow.png" alt="" />
                                <img className="shareimg" src="/assets/wechat/pic_share.png" alt="" />
                                <div>点击右上角可以分享哦！</div>
                            </div>
                        </div>

                    </div>
                </div>
            </div >
        )
    }
}
ReactDom.render(<Creditcardshare />, document.getElementById("app"));